package com.oauth.service.application.registry;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.oauth.logging.OAuthLogger;
import com.oauth.service.application.registry.beans.ApplicationInfoBean;

/**
 * ************************ GLOBAL REGISTRATOIN SERVICE
 * *************************
 * 
 * Use this service to get information about all application that are registered
 * across the site.
 * 
 * @author asanthan
 * 
 */
public class GlobalRegistryServiceImpl implements GlobalRegistryService<ApplicationInfoBean> {

	Map<Long, ApplicationInfoBean> registeredApplicationMap = new HashMap<Long, ApplicationInfoBean>();

	private OAuthLogger mLogger = OAuthLogger.getLogger(this.getClass());

	@Override
	public List<ApplicationInfoBean> getApplicationInfo(Set<Long> pApplicationIdSet) {
		List<ApplicationInfoBean> applicationList = new ArrayList<ApplicationInfoBean>();
		if (pApplicationIdSet != null) {
			for (Long key : pApplicationIdSet) {
				ApplicationInfoBean applicationInfoBean = registeredApplicationMap.get(key);
				if (applicationInfoBean != null) {
					applicationList.add(applicationInfoBean);
				} else {
					mLogger
							.info("Warning , Trying to get unregistered application with key="
									+ key);
				}
			}
		}
		return applicationList;
	}

	@Override
	public ApplicationInfoBean getApplicationInfo(Long pApplicationId) {
		return registeredApplicationMap.get(pApplicationId);
	}

	public Set<Long> getRegisterdApplicationId() {
		return new HashSet<Long>(registeredApplicationMap.keySet());
	}

	public Collection<ApplicationInfoBean> getRegisterdApplication() {
		return new ArrayList<ApplicationInfoBean>(registeredApplicationMap.values());
	}

	@Override
	public void registerApplication(ApplicationInfoBean pApplicationInfoBean) {
		if (registeredApplicationMap.containsKey(pApplicationInfoBean.getKey())) {
			mLogger.info("Warning, Application is already registered with key="
					+ pApplicationInfoBean.getKey());
		} else {
			mLogger.info("REGISTERED:" + pApplicationInfoBean.getName() + "\tService="
					+ pApplicationInfoBean.getAppGlobalService());
			registeredApplicationMap.put(pApplicationInfoBean.getKey(), pApplicationInfoBean);
		}
	}
}
